package com.aloda.utils;

import com.aloda.constant.ErrorCode;
import com.aloda.exception.BaseException;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.awt.*;
import java.io.IOException;
import java.util.Iterator;

public class ImageUtils {

    // 获取图片格式
    public static String getImageFormat(MultipartFile file) {
        try (ImageInputStream iis = ImageIO.createImageInputStream(file.getInputStream())) {
            Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);
            if (readers.hasNext()) {
                return readers.next().getFormatName();
            }
        } catch (IOException e) {
            throw new BaseException(ErrorCode.SYSTEM_ERROR);
        }
        return null; // 如果无法识别格式，则返回null
    }

    // 获取图片宽度
    public static Integer getImageWidth(MultipartFile file) {
        try (ImageInputStream iis = ImageIO.createImageInputStream(file.getInputStream())) {
            Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);
            if (readers.hasNext()) {
                ImageReader reader = readers.next();
                reader.setInput(iis);
                return reader.getWidth(reader.getMinIndex());
            }
        } catch (IOException e) {
            throw new BaseException(ErrorCode.SYSTEM_ERROR);
        }
        return null; // 如果无法获取宽度，则返回null
    }

    // 获取图片高度
    public static Integer getImageHeight(MultipartFile file) {
        try (ImageInputStream iis = ImageIO.createImageInputStream(file.getInputStream())) {
            Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);
            if (readers.hasNext()) {
                ImageReader reader = readers.next();
                reader.setInput(iis);
                return reader.getHeight(reader.getMinIndex());
            }
        } catch (IOException e) {
            throw new BaseException(ErrorCode.SYSTEM_ERROR);
        }
        return null; // 如果无法获取高度，则返回null
    }

    // 获取图片体积（以字节为单位）
    public static Long getImageSize(MultipartFile file) {
        return file.getSize(); // MultipartFile 提供了getSize()方法直接获取文件大小
    }

    // 获取图片名称
    public static String getImageName(MultipartFile file) {
        return file.getOriginalFilename(); // MultipartFile 提供了getOriginalFilename()方法直接获取原始文件名
    }
}
